const dataService = require('../services/dataService');
const storageService = require('../services/storageService');
const schedulerService = require('../services/schedulerService');
const { setupLogger } = require('../utils/logger');

class ApiController {
  constructor() {
    this.logger = setupLogger();
  }

  // 健康检查
  async health(ctx) {
    try {
      const status = {
        status: 'ok',
        timestamp: new Date().toISOString(),
        version: '1.0.0',
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        scheduler: schedulerService.getStatus(),
        lastDataUpdate: dataService.getLastUpdate()
      };

      ctx.body = {
        success: true,
        data: status
      };
    } catch (error) {
      this.logger.error('健康检查失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取数据概览
  async getSummary(ctx) {
    try {
      const data = await storageService.loadCompactData();
      
      if (!data) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '数据未找到'
        };
        return;
      }

      ctx.body = {
        success: true,
        data: {
          summary: data.summary,
          metadata: data.metadata,
          lastUpdate: data.lastUpdate
        }
      };
    } catch (error) {
      this.logger.error('获取数据概览失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取代币数据
  async getTokens(ctx) {
    try {
      const { 
        symbol, 
        category, 
        minScore = 0, 
        maxScore = 100,
        sortBy = 'score',
        order = 'desc',
        limit = 50, 
        offset = 0 
      } = ctx.query;

      const data = await storageService.loadData();
      
      if (!data || !data.tokens) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '代币数据未找到'
        };
        return;
      }

      let tokens = data.tokens;

      // 应用过滤器
      if (symbol) {
        tokens = tokens.filter(token => 
          token.symbol.toLowerCase().includes(symbol.toLowerCase())
        );
      }

      if (category) {
        tokens = tokens.filter(token => token.category === category);
      }

      tokens = tokens.filter(token => {
        const score = token.score || 0;
        return score >= parseFloat(minScore) && score <= parseFloat(maxScore);
      });

      // 排序
      tokens.sort((a, b) => {
        const aVal = a[sortBy] || 0;
        const bVal = b[sortBy] || 0;
        
        if (order === 'desc') {
          return bVal - aVal;
        } else {
          return aVal - bVal;
        }
      });

      // 分页
      const total = tokens.length;
      const paginatedTokens = tokens.slice(
        parseInt(offset), 
        parseInt(offset) + parseInt(limit)
      );

      ctx.body = {
        success: true,
        data: {
          tokens: paginatedTokens,
          pagination: {
            total,
            limit: parseInt(limit),
            offset: parseInt(offset),
            hasMore: parseInt(offset) + parseInt(limit) < total
          },
          filters: {
            symbol,
            category,
            minScore,
            maxScore,
            sortBy,
            order
          }
        }
      };
    } catch (error) {
      this.logger.error('获取代币数据失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取单个代币详情
  async getTokenDetail(ctx) {
    try {
      const { symbol } = ctx.params;
      
      const data = await storageService.loadData();
      
      if (!data || !data.tokens) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '数据未找到'
        };
        return;
      }

      const token = data.tokens.find(t => 
        t.symbol.toLowerCase() === symbol.toLowerCase()
      );

      if (!token) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: `代币 ${symbol} 未找到`
        };
        return;
      }

      ctx.body = {
        success: true,
        data: token
      };
    } catch (error) {
      this.logger.error('获取代币详情失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取聪明钱数据
  async getSmartMoney(ctx) {
    try {
      const { 
        minScore = 0,
        maxScore = 100,
        riskLevel,
        tags,
        sortBy = 'smartScore',
        order = 'desc',
        limit = 20, 
        offset = 0 
      } = ctx.query;

      const data = await storageService.loadData();
      
      if (!data || !data.smartMoney) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '聪明钱数据未找到'
        };
        return;
      }

      let smartMoney = data.smartMoney;

      // 应用过滤器
      smartMoney = smartMoney.filter(wallet => {
        const score = wallet.smartScore || 0;
        return score >= parseFloat(minScore) && score <= parseFloat(maxScore);
      });

      if (riskLevel) {
        smartMoney = smartMoney.filter(wallet => wallet.riskLevel === riskLevel);
      }

      if (tags) {
        const tagList = tags.split(',').map(tag => tag.trim());
        smartMoney = smartMoney.filter(wallet => 
          tagList.some(tag => wallet.tags.includes(tag))
        );
      }

      // 排序
      smartMoney.sort((a, b) => {
        const aVal = a[sortBy] || 0;
        const bVal = b[sortBy] || 0;
        
        if (order === 'desc') {
          return bVal - aVal;
        } else {
          return aVal - bVal;
        }
      });

      // 分页
      const total = smartMoney.length;
      const paginatedData = smartMoney.slice(
        parseInt(offset), 
        parseInt(offset) + parseInt(limit)
      );

      ctx.body = {
        success: true,
        data: {
          smartMoney: paginatedData,
          pagination: {
            total,
            limit: parseInt(limit),
            offset: parseInt(offset),
            hasMore: parseInt(offset) + parseInt(limit) < total
          },
          filters: {
            minScore,
            maxScore,
            riskLevel,
            tags,
            sortBy,
            order
          }
        }
      };
    } catch (error) {
      this.logger.error('获取聪明钱数据失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取聪明钱详情
  async getSmartMoneyDetail(ctx) {
    try {
      const { address } = ctx.params;
      
      const data = await storageService.loadData();
      
      if (!data || !data.smartMoney) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '数据未找到'
        };
        return;
      }

      const wallet = data.smartMoney.find(w => w.address === address);

      if (!wallet) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: `钱包 ${address} 未找到`
        };
        return;
      }

      ctx.body = {
        success: true,
        data: wallet
      };
    } catch (error) {
      this.logger.error('获取聪明钱详情失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取市场数据
  async getMarketData(ctx) {
    try {
      const data = await storageService.loadData();
      
      if (!data || !data.marketData) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '市场数据未找到'
        };
        return;
      }

      ctx.body = {
        success: true,
        data: data.marketData
      };
    } catch (error) {
      this.logger.error('获取市场数据失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取趋势分析
  async getTrends(ctx) {
    try {
      const data = await storageService.loadData();
      
      if (!data || !data.trends) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '趋势数据未找到'
        };
        return;
      }

      ctx.body = {
        success: true,
        data: data.trends
      };
    } catch (error) {
      this.logger.error('获取趋势数据失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取风险分析
  async getRisks(ctx) {
    try {
      const { severity, type } = ctx.query;
      
      const data = await storageService.loadData();
      
      if (!data || !data.risks) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '风险数据未找到'
        };
        return;
      }

      let risks = data.risks;

      // 应用过滤器
      if (severity) {
        risks = risks.filter(risk => risk.severity === severity);
      }

      if (type) {
        risks = risks.filter(risk => risk.type === type);
      }

      ctx.body = {
        success: true,
        data: {
          risks,
          summary: {
            total: risks.length,
            bySeverity: this.groupBy(risks, 'severity'),
            byType: this.groupBy(risks, 'type')
          }
        }
      };
    } catch (error) {
      this.logger.error('获取风险数据失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 搜索功能
  async search(ctx) {
    try {
      const { q, type = 'all', limit = 20 } = ctx.query;
      
      if (!q || q.trim().length < 2) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          error: '搜索关键词至少需要2个字符'
        };
        return;
      }

      const data = await storageService.loadData();
      
      if (!data) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '数据未找到'
        };
        return;
      }

      const results = {
        tokens: [],
        smartMoney: [],
        total: 0
      };

      const keyword = q.toLowerCase();

      // 搜索代币
      if (type === 'all' || type === 'tokens') {
        if (data.tokens) {
          results.tokens = data.tokens.filter(token => 
            token.symbol.toLowerCase().includes(keyword) ||
            token.name.toLowerCase().includes(keyword)
          ).slice(0, parseInt(limit));
        }
      }

      // 搜索聪明钱
      if (type === 'all' || type === 'smartMoney') {
        if (data.smartMoney) {
          results.smartMoney = data.smartMoney.filter(wallet => 
            wallet.address.toLowerCase().includes(keyword) ||
            (wallet.nickname && wallet.nickname.toLowerCase().includes(keyword)) ||
            wallet.tags.some(tag => tag.toLowerCase().includes(keyword))
          ).slice(0, parseInt(limit));
        }
      }

      results.total = results.tokens.length + results.smartMoney.length;

      ctx.body = {
        success: true,
        data: results,
        query: {
          keyword: q,
          type,
          limit: parseInt(limit)
        }
      };
    } catch (error) {
      this.logger.error('搜索失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 刷新数据
  async refreshData(ctx) {
    try {
      const result = await dataService.refreshData();
      
      ctx.body = {
        success: true,
        message: '数据刷新已启动',
        data: result
      };
    } catch (error) {
      this.logger.error('刷新数据失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取文件统计
  async getFileStats(ctx) {
    try {
      const stats = await storageService.getFileStats();
      
      ctx.body = {
        success: true,
        data: stats
      };
    } catch (error) {
      this.logger.error('获取文件统计失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 下载数据文件
  async downloadFile(ctx) {
    try {
      const { type } = ctx.params;
      const config = require('../config/config');
      const path = require('path');
      
      let filePath;
      let fileName;
      let contentType;
      
      switch (type) {
        case 'json':
          filePath = path.join(config.storage.dataDir, config.storage.jsonFile);
          fileName = config.storage.jsonFile;
          contentType = 'application/json';
          break;
        case 'excel':
          filePath = path.join(config.storage.dataDir, config.storage.excelFile);
          fileName = config.storage.excelFile;
          contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
          break;
        case 'compact':
          filePath = path.join(config.storage.dataDir, 'compact_' + config.storage.jsonFile);
          fileName = 'compact_' + config.storage.jsonFile;
          contentType = 'application/json';
          break;
        default:
          ctx.status = 400;
          ctx.body = {
            success: false,
            error: '不支持的文件类型'
          };
          return;
      }

      const fs = require('fs').promises;
      
      try {
        await fs.access(filePath);
      } catch {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '文件不存在'
        };
        return;
      }

      ctx.set('Content-Type', contentType);
      ctx.set('Content-Disposition', `attachment; filename="${fileName}"`);
      
      const fileContent = await fs.readFile(filePath);
      ctx.body = fileContent;
      
    } catch (error) {
      this.logger.error('下载文件失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 获取统计信息
  async getStats(ctx) {
    try {
      const data = await storageService.loadData();
      
      if (!data) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: '数据未找到'
        };
        return;
      }

      const stats = {
        tokens: {
          total: data.tokens?.length || 0,
          byCategory: this.groupBy(data.tokens || [], 'category'),
          avgScore: this.calculateAverage(data.tokens || [], 'score'),
          topScoring: (data.tokens || []).slice(0, 5).map(t => ({
            symbol: t.symbol,
            score: t.score
          }))
        },
        smartMoney: {
          total: data.smartMoney?.length || 0,
          byRiskLevel: this.groupBy(data.smartMoney || [], 'riskLevel'),
          avgScore: this.calculateAverage(data.smartMoney || [], 'smartScore'),
          topPerforming: (data.smartMoney || []).slice(0, 5).map(w => ({
            address: w.address.substring(0, 8) + '...',
            score: w.smartScore
          }))
        },
        risks: {
          total: data.risks?.length || 0,
          bySeverity: this.groupBy(data.risks || [], 'severity'),
          byType: this.groupBy(data.risks || [], 'type')
        },
        lastUpdate: data.lastUpdate,
        dataAge: data.lastUpdate ? 
          Math.floor((Date.now() - new Date(data.lastUpdate).getTime()) / 1000 / 60) : null
      };

      ctx.body = {
        success: true,
        data: stats
      };
    } catch (error) {
      this.logger.error('获取统计信息失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  // 辅助方法
  groupBy(array, key) {
    return array.reduce((groups, item) => {
      const value = item[key] || 'unknown';
      groups[value] = (groups[value] || 0) + 1;
      return groups;
    }, {});
  }

  calculateAverage(array, key) {
    if (array.length === 0) return 0;
    const sum = array.reduce((total, item) => total + (item[key] || 0), 0);
    return parseFloat((sum / array.length).toFixed(2));
  }
}

module.exports = new ApiController();

